<template>
  <div class="consultation">
    <h2>用户管理</h2>
    <div class="consultation-block">
      <div class="table" v-loading="tableLoading">
        <el-table size="mini" :data="tableData" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="username" label="用户名"> </el-table-column>
          <el-table-column prop="password" label="密码"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="warning"
                size="mini"
                @click="updateData(scope.row)"
                >修改</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="isVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input type="text" v-model="ruleForm.pass"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="text" v-model="ruleForm.checkPass"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="查看"
      :visible.sync="isVisible2"
      width="80%"
      :before-close="handleClose2"
    >
      <div>
        <download-excel
          class="export-excel-wrapper"
          :data="tableDataModal"
          :fields="json_fields"
          :header="title"
          :name="title + '.xls'"
        >
          <el-button size="mini" type="success">导出</el-button>
        </download-excel>
      </div>
      <div class="table">
        <el-table
          size="mini"
          :data="tableDataModal"
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column
            :label="col"
            :prop="index + ''"
            :key="index"
            v-for="(col, index) in columnModel"
          >
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addUser, getUser, deleteUser, updateUser, getModel } from "../service.js";
export default {
  name: "home",
  mounted() {
    this.refreshTable();
    this.getModel()
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableLoading: false,
      isVisible: false,
      dialogTitle: "",
      ruleForm: {
        username: "",
        pass: "",
        checkPass: "",
        title: "",
        column: "",
        tableId: ''
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        tableId: [
          { required: true, message: "请添加表格列", trigger: "change" },
        ],
      },
      json_fields: {},
      columns: [],
      inputValue: "",
      inputVisible: false,
      isVisible2: false,
      tableDataModal: [],
      columnModel: [],
      title: '',
      modelList: []
    };
  },
  methods: {
    getModel() {
      getModel().then(res => {
        this.modelList = res.data
        console.log(this.modelList)
      })
    },
    addUser() {
      this.isVisible = true;
      this.ruleForm = {
        username: "",
        pass: "",
        checkPass: "",
        title: "",
        column: "",
      }
      this.dialogTitle = "新建用户";
    },
    handleClose() {
      this.isVisible = false;
    },
    handleClose2() {
      this.isVisible2 = false;
    },
    handleCurrentChange() {},
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateUser(this.ruleForm.id, {
            username: this.ruleForm.username,
            password: this.ruleForm.pass,
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success("编辑成功");
              this.refreshTable();
              this.isVisible = false;
            }
          });
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    closeTag(tag) {
      this.columns.splice(this.columns.indexOf(tag), 1);
      if (this.columns.length) {
        this.ruleForm.column = JSON.stringify(this.columns);
      } else {
        this.ruleForm.column = "";
      }
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.columns.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
      this.ruleForm.column = JSON.stringify(this.columns);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    refreshTable() {
      getUser().then((res) => {
        this.tableData = res.code === 200 ? res.data : [];
      });
    },
    bc2() {
      this.isVisible2 = false;
    },
    detail(row) {
      this.json_fields = {}
      this.columnModel = JSON.parse(row.column);
      for (let i = 0;i < this.columnModel.length;i++) {
        this.json_fields[this.columnModel[i]] = i + ''
      }
      this.tableDataModal = JSON.parse(row.data);
      this.title = row.title
      this.isVisible2 = true;
    },
    formatStatus(row) {
      if (row.username === 'admin') {
        return "-";
      }
      if (row.data === "" || row.data === "[]") {
        return "未填写";
      } else {
        return "已填写";
      }
    },
    download() {

    },
    updateData(row) {
      this.dialogTitle = '修改'
      this.ruleForm.username = row.username;
      this.ruleForm.pass = row.password;
      this.ruleForm.checkPass = row.password;
      this.ruleForm.title = row.title;
      this.ruleForm.column = row.column;
      this.ruleForm.id = row._id;
      this.ruleForm.data = row.data;
      this.columns = JSON.parse(row.column)
      this.isVisible = true
    },
    deleteData(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUser(row._id).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.refreshTable()
            }
          })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    }
  },
};
</script>

<style scoped>
h2 {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
.consultation-block {
  width: 90%;
  margin-left: 5%;
}

.pagination {
  text-align: center;
  margin-top: 20px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
